import { ref, computed, watch } from 'vue'
import { getAutocompleteSuggestions, applySuggestion } from '../utils/sqlAutocomplete'

/**
 * SQL自动完成组合式函数
 * @param {Object} options - 配置选项
 * @returns {Object} 自动完成相关的响应式数据和方法
 */
export default function useSqlAutocomplete(options = {}) {
  const {
    content = ref(''),
    cursorPosition = ref(0),
    enabled = ref(true),
    context = {}
  } = options

  // 响应式状态
  const showSuggestions = ref(false)
  const suggestions = ref([])
  const selectedIndex = ref(0)
  const isTriggerKey = ref(false)

  // 自动完成触发键
  const triggerKeys = ['.', ' ']
  
  // 更新建议
  const updateSuggestions = () => {
    if (!enabled.value || !content.value || cursorPosition.value <= 0) {
      hideSuggestions()
      return
    }

    // 创建一个上下文对象，包含表、列和数据库类型信息
    const fullContext = {
      tables: context.tables || [],
      columns: context.columns || [],
      dbType: context.dbType || ''
    }

    const newSuggestions = getAutocompleteSuggestions(
      content.value, 
      cursorPosition.value,
      fullContext
    )

    if (newSuggestions.length > 0) {
      suggestions.value = newSuggestions
      selectedIndex.value = 0
      showSuggestions.value = true
    } else {
      hideSuggestions()
    }
  }

  // 隐藏建议
  const hideSuggestions = () => {
    showSuggestions.value = false
    suggestions.value = []
    selectedIndex.value = 0
  }

  // 选择下一个建议
  const selectNextSuggestion = () => {
    if (suggestions.value.length === 0) return
    
    selectedIndex.value = (selectedIndex.value + 1) % suggestions.value.length
  }

  // 选择上一个建议
  const selectPrevSuggestion = () => {
    if (suggestions.value.length === 0) return
    
    selectedIndex.value = (selectedIndex.value - 1 + suggestions.value.length) % suggestions.value.length
  }

  // 应用当前选择的建议
  const applySelectedSuggestion = () => {
    if (!showSuggestions.value || suggestions.value.length === 0) return false

    const suggestion = suggestions.value[selectedIndex.value]
    const result = applySuggestion(content.value, cursorPosition.value, suggestion)
    
    if (result) {
      content.value = result.input
      cursorPosition.value = result.cursorPosition
      hideSuggestions()
      return true
    }
    
    return false
  }

  // 应用指定的建议
  const applySuggestionByIndex = (index) => {
    if (!showSuggestions.value || !suggestions.value[index]) return false
    
    selectedIndex.value = index
    return applySelectedSuggestion()
  }

  // 处理鼠标悬停事件
  const handleMouseOver = (index) => {
    if (index >= 0 && index < suggestions.value.length) {
      selectedIndex.value = index
    }
  }

  // 处理鼠标点击事件
  const handleMouseClick = (index) => {
    if (index >= 0 && index < suggestions.value.length) {
      selectedIndex.value = index
      return applySelectedSuggestion()
    }
    return false
  }

  // 处理键盘事件
  const handleKeyDown = (event) => {
    if (!enabled.value) return
    
    // 检查是否是触发键
    isTriggerKey.value = triggerKeys.includes(event.key)
    
    // 已显示建议时处理方向键和回车
    if (showSuggestions.value && suggestions.value.length > 0) {
      switch (event.key) {
        case 'ArrowDown':
          event.preventDefault()
          selectNextSuggestion()
          return true
        case 'ArrowUp':
          event.preventDefault()
          selectPrevSuggestion()
          return true
        case 'Tab':
        case 'Enter':
          if (showSuggestions.value) {
            event.preventDefault()
            applySelectedSuggestion()
            return true
          }
          break
        case 'Escape':
          event.preventDefault()
          hideSuggestions()
          return true
      }
    }
    
    return false
  }

  // 处理输入事件
  const handleInput = () => {
    if (!enabled.value) return
    
    if (isTriggerKey.value || content.value.length >= 2) {
      updateSuggestions()
    } else {
      hideSuggestions()
    }
    
    isTriggerKey.value = false
  }

  // 当前选中的建议
  const selectedSuggestion = computed(() => {
    if (suggestions.value.length === 0) return null
    return suggestions.value[selectedIndex.value]
  })

  // 监听内容变化
  watch(content, () => {
    if (enabled.value) {
      handleInput()
    }
  })

  // 监听光标位置变化
  watch(cursorPosition, () => {
    if (enabled.value && showSuggestions.value) {
      updateSuggestions()
    }
  })

  return {
    showSuggestions,
    suggestions,
    selectedIndex,
    selectedSuggestion,
    updateSuggestions,
    hideSuggestions,
    selectNextSuggestion,
    selectPrevSuggestion,
    applySelectedSuggestion,
    applySuggestionByIndex,
    handleMouseOver,
    handleMouseClick,
    handleKeyDown,
    handleInput
  }
} 